<?php
namespace app\admin\controller;

use app\common\controller\SysAction;
use app\common\model\AgentWallet;
use app\common\model\AgentInfo;
use app\common\model\Agent as A;
use think\Db;

class Agent extends SysAction
{
    protected $modelClass = '\app\common\model\Agent';
    
    public function initialize()
    {
        parent::initialize();
    }

    public function index(){
    	$where = [];
        if (input('get.search')){
            $where[] = ['webname|url|email', 'like', '%'.input('get.search').'%'];
        }
        if (input('get._sort')){
            $order = explode(',', input('get._sort'));
            $order = $order[0].' '.$order[1];
        }else{
            $order = 'id asc';
        }
        $dataList = $this->cModel->where($where)->order($order)->paginate('', false, page_param());
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }
    
    /**
     * @Title: create
     * @Description: todo(添加加盟商)
     * @return mixed
     * @author 若谷
     * @date 2019年6月6日
     * @throws
     */
    public function create()
    {
        if (request()->isPost()){
            Db::startTrans();
            try{
                $data = input('post.');
                $result = $this->validate($data, 'app\common\validate\\'.CONTROLLER_NAME.'.add');
                if(true !== $result){
                    return ajax_return($result);
                }
                $result = $this->cModel->allowField(true)->save($data);
                $wallet = new AgentWallet();
                $money = [
                    'agent_id' => $this->cModel->id
                ];
                $result2 = $wallet->allowField(true)->save($money);
                // 提交事务
                if ($result && $result2){
                    Db::commit();
                    return ajax_return(lang('action_success'), url('index'));
                }else{
                    return ajax_return($this->cModel->getError());
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajax_return($e->getMessage());
            }
        }else{
            return $this->fetch('create');
        }
    }

    /**
     * @Title: create
     * @Description: todo(编辑加盟商)
     * @return mixed
     * @author 若谷
     * @date 2019年6月10日
     * @throws
     */
    public function edit($id)
    {
        if (request()->isPost()){
            $data = input('post.');
            if ($data['actions'] == 'password'){    //修改密码
                if ( $data['id'] != UID ){          //修改他人密码需验证旧密码
                    $oldData = $this->cModel->where(['id' => $data['id'], 'password' => md5($data['oldpassword'])])->find();
                    if (empty($oldData)){
                        ajax_return(lang('oldpassword_val'));
                    }
                }
                $result = $this->validate($data, 'app\common\validate\\'.CONTROLLER_NAME.'.password');
                if(true !== $result){
                    return ajax_return($result);
                }
                $result = $this->cModel->allowField(true)->save($data, $data['id']);
            }elseif ($data['actions'] == 'infos'){   //修改店铺信息
                $uiModel = new AgentInfo();
                if ($data['address']) {
                    $location = $this->getAddress($data['address']);
                    $data['lng'] = $location['lng'];
                    $data['lat'] = $location['lat'];
                }
                $info = $uiModel->where("agent_id",$data['id'])->find();
                if ($info) {
                    $result = $this->validate($data, 'app\common\validate\AgentInfo.edit');
                    if(true !== $result){
                        return ajax_return($result);
                    }
                    $result = $uiModel->allowField(true)->save($data, ['agent_id' => $data['id']]);
                }else{
                    $data['agent_id'] = $data['id'];
                    $result = $this->validate($data, 'app\common\validate\AgentInfo.add');
                    if(true !== $result){
                        return ajax_return($result);
                    }
                    $result = $uiModel->allowField(true)->save($data);
                }
                if ($result){
                    return ajax_return(lang('action_success'), url('index'));
                }else{
                    return ajax_return($uiModel->getError());
                }
            }else{   //修改信息
                if (count($data) == 2){
                    foreach ($data as $k =>$v){
                        $fv = $k!='id' ? $k : '';
                    }
                    $result = $this->validate($data, 'app\common\validate\\'.CONTROLLER_NAME.'.'.$fv);
                    if(true !== $result){
                        return ajax_return($result);
                    }
                    $result = $this->cModel->allowField(true)->save($data, $data['id']);
                }else{
                    $result = $this->validate($data, 'app\common\validate\\'.CONTROLLER_NAME.'.edit');
                    if(true !== $result){
                        return ajax_return($result);
                    }
                    $result = $this->cModel->allowField(true)->save($data, $data['id']);
                }
            }
            if ($result){
                return ajax_return(lang('action_success'), url('index'));
            }else{
                return ajax_return($this->cModel->getError());
            }
        }else{
            $data = $this->cModel->get($id);
            $this->assign('data', $data);
            return $this->fetch();
        }
    }

    /**
     * @Title: delete
     * @Description: todo(软删除加盟商)
     * @return mixed
     * @author 若谷
     * @date 2019年6月10日
     * @throws
     */
    public function delete()
    {
        if (request()->isPost()){
            $id = input('id');
            if (isset($id) && !empty($id)){
                Db::startTrans();
                try{
                    $id_arr = explode(',', $id);

                    $result = A::destroy($id_arr);              //删除主表数据
                    $result1 = AgentWallet::destroy($id_arr);       //删除钱包
                    $result2 = AgentInfo::destroy($id_arr);         //删除加盟商信息表

                    // 提交事务
                    if ($result && $result1){
                        Db::commit();
                        return ajax_return(lang('action_success'), url('index'));
                    }else{
                        return ajax_return($this->cModel->getError());
                    }
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return ajax_return($e->getMessage());
                }
            }
        }
    }

    /**
     * @Title: depot
     * @Description: todo(回收站)
     * @return mixed
     * @author 若谷
     * @date 2019年6月10日
     * @throws
     */
    public function depot(){
        $where = [];
        if (input('get.search')){
            $where[] = ['webname|url|email', 'like', '%'.input('get.search').'%'];
        }
        if (input('get._sort')){
            $order = explode(',', input('get._sort'));
            $order = $order[0].' '.$order[1];
        }else{
            $order = 'id asc';
        }
        $dataList = A::onlyTrashed()->where($where)->order($order)->paginate('', false, page_param());
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }

    /**
     * @Title: recover
     * @Description: todo(恢复加盟商)
     * @return mixed
     * @author 若谷
     * @date 2019年6月10日
     * @throws
     */
    public function recover($id){
        if (request()->isPost()) {
            $id = input('id');
            Db::startTrans();
            try{
                $agent  = A::onlyTrashed()->find($id);
                $result = $agent->restore();

                $wallet  = AgentWallet::onlyTrashed()->where("agent_id",$id)->find();
                $result1 = $wallet->restore();

                $info    = AgentInfo::onlyTrashed()->where("agent_id",$id)->find();
                if ($info) {
                    $result2 = $info->restore();
                }

                // 提交事务
                if ($result && $result1){
                    Db::commit();
                    return ajax_return(lang('action_success'), url('index'));
                }else{
                    return ajax_return($this->cModel->getError());
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajax_return($e->getMessage());
            }
        }
    }

    /**
     * @Title: getAddress
     * @Description: todo(获取地址经纬度信息)
     * @return mixed
     * @author 若谷
     * @date 2019年6月10日
     * @throws
     */
    protected function getAddress($address=""){
        $key = confv('key','others');
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?key=".$key."&address=".$address;
        $result = httpRequest($url);
        $result = json_decode($result,1);
        if ($result['status'] == 0) {
            $location = $result['result']['location'];
        }
        return $location;
    }
}